// ./utils/alerter.util.js

const nodemailer = require('nodemailer');
require('dotenv').config();

// 创建邮件传输器
const transporter = nodemailer.createTransport({
    host: process.env.MAIL_HOST,
    port: process.env.MAIL_PORT,
    secure: process.env.MAIL_SECURE === 'true', // true for 465, false for other ports
    auth: {
        user: process.env.MAIL_USER,
        pass: process.env.MAIL_PASS,
    },
});

/**
 * 发送系统告警邮件
 * @param {string} subject - 邮件主题
 * @param {string} text - 邮件正文
 */
const sendAlert = async (subject, text) => {
    const mailOptions = {
        from: `"${process.env.MAIL_USER}"`,
        to: process.env.ALERT_RECIPIENT,
        subject: `🚨 服务器告警: ${subject}`,
        html: `<pre>${text}</pre>`, // 使用 <pre> 标签保留格式
    };

    try {
        await transporter.sendMail(mailOptions);
        // 通常不在告警函数中记录 info 日志，避免循环依赖或日志爆炸
        // console.log(`[告警]: 邮件发送成功 - ${subject}`);
    } catch (error) {
        console.error(`[告警]: 邮件发送失败! 错误: ${error.message}`);
    }
};

module.exports = { sendAlert };
